package middleware

import (
	"errors"
	"gitee.com/CrazyMage/blog-service/pkg/app"
	"gitee.com/CrazyMage/blog-service/pkg/errcode"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"log"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		response := app.NewResponse(c)

		var (
			token  string
			exist  bool
			claims *app.Claims
			err    error
			ecode  = errcode.Success
		)

		// 先从query参数获取token
		if token, exist = c.GetQuery("token"); !exist {
			// 如果query中没有，再从header中获取token
			token = c.GetHeader("token")
		}

		// 检查最终token是否为空
		if token == "" {
			response.ToErrorResponse(errcode.AuthorizedTokenNotExist)
			log.Println("token is null")
			c.Abort()
			return
		}

		//解析token
		claims, err = app.ParseToken(token)
		if err != nil {
			switch err.(*jwt.ValidationError).Errors {
			case jwt.ValidationErrorExpired:
				ecode = errcode.UnauthorizedTokenTimeout
			default:
				ecode = errcode.UnauthorizedTokenError
			}
		}

		if !errors.Is(ecode, errcode.Success) {
			response.ToErrorResponse(ecode)
			c.Abort()
			return
		}

		c.Set("user_id", claims.UserId)
		c.Next()

	}
}
